package com.minimalist.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * 全局过滤器
 *
 * @author minimalist
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(MyGlobalFilter.class);


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        String method = request.getMethod().name();
        String requestId = UUID.randomUUID().toString();

        log.info("请求开始 - [{}] {} {}", requestId, method, path);

        // 添加请求ID到请求头
        ServerHttpRequest newRequest = request.mutate()
                .header("X-Request-Id", requestId)
                .build();

        ServerWebExchange newExchange = exchange.mutate()
                .request(newRequest)
                .build();

        // 使用 doOnSuccess 而不是 doFinally，避免在响应已提交后再次处理
        return chain.filter(newExchange)
                .doOnSuccess(v -> log.info("请求结束 - [{}] {} {}", requestId, method, path))
                .doOnError(e -> log.error("请求异常 - [{}] {} {} - 错误: {}",
                        requestId, method, path, e.getMessage()));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
